package com.yungu.swift.lbs.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.lbs.service.ThirdPartyService;
import com.yungu.swift.utils.HttpUtils;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static com.yungu.swift.lbs.config.NacosListener.THIRDPARTY_CONFIG;

/**
 * @author : cuixiuyin
 * @date : 2019/4/17
 */
@Slf4j
@Service
public class ThirdPartyServiceImpl implements ThirdPartyService {

    @Override
    public ResponseData<String> getShortUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            throw new UnsupportedOperationException("url is not empty");
        }
        String baiduUrl = "https://dwz.cn/admin/v2/create";
        Map<String, String> headerMap = new HashMap<>(2);
        headerMap.put("Token", "ecd4ea68c4a650fbb6c2a6968690a18b");
        try {
            Map<String, Object> paramMap = MapUtils.build("Url", url);
            paramMap.put("_JSON_STRING", JsonUtils.writeJsonStr(paramMap));
            Map<String, Object> objectMap = HttpUtils.post(baiduUrl, 3, paramMap, headerMap);
            Object status = objectMap.get("status");
            if (status != null && Integer.parseInt(status.toString()) == 200) {
                String responseString = objectMap.get("result").toString();
                JsonNode jsonNode = JsonUtils.readNode(responseString);
                return ResponseData.buildSuccessResponse(jsonNode.get("ShortUrl").toString());
            }
            log.warn("百度获取短链接失败，url:{}", url);
            String sinaUrl = "https://c.api.weibo.com/2/short_url/shorten/biz.json??";
            String requestParams = "source=" + THIRDPARTY_CONFIG.getSinaAppKey() + "&url_long=" + URLEncoder.encode(url, "UTF-8");
            String responseString = HttpUtils.getResponseString(sinaUrl + requestParams);
            JsonNode jsonNode = JsonUtils.readNode(responseString);
            ArrayNode arrayNode = (ArrayNode) jsonNode.get("urls");
            if (arrayNode != null && arrayNode.size() > 0) {
                url = arrayNode.get(0).get("url_short").asText();
            }
        } catch (Exception e) {
            log.error("getShortUrl error,url:{}", url, e);
        }
        return ResponseData.buildSuccessResponse(url);
    }
}
